package cn.jathlon.math;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5 code
 * @author tuxiao.czz
 *
 */
public class MD5 {
	public static String getMD5(byte[] source) {
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' }; 

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2]; 
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			s = new String(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	///////////
	/**
	 * Returns the hexadecimal representation of an MD5 hash.
	 *
	 * @param pass input string
	 * @return hashed string
	 */
	static public String md5(String pass){
		return hex(calcMd5(pass));
	}

	/**
	 * make an md5 hash from a string
	 *
	 * @param pass string to be hashed
	 * @return the hash as an byte array
	 */
	static private byte[] calcMd5(String pass){
		try{
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(pass.getBytes(),0,pass.length());
			byte[] hash = digest.digest();
			return hash;
		} catch(NoSuchAlgorithmException e){
			System.err.println("No MD5 algorithm found");
			throw new RuntimeException(e);
		}
	}


	/**
	 * Convert an array of bytes to an uppercase hexadecimal representation
	 *
	 * @param array a byte array
	 * @return the byte array as a hexadecimal string representation
	 */
	static private String hex(byte[] array) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < array.length; ++i) {
			sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1,3));
		}
		return sb.toString();
	}

	
	
	public static void main(String[] args) {
		System.out.println(MD5.getMD5("http://topic.csdn.net/u/20110314/22/F40DDE47-4AD4-4E9E-B5CF-F24B1E343240.html".getBytes()));;
	}
	
}
